package com.kavian.common.util;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * HttpClient的工具类
 * 
 * @author kavian
 * 
 */
public class HttpClientUtil {

	private static HttpClient httpclient = null;

	public HttpClientUtil() {
	}

	/**
	 * httpClient生成
	 */
	public static void httpClient() {
		if (null != httpclient) {
			return;
		}

		httpclient = new DefaultHttpClient();
	}

	/**
	 * httpGet方法返回网页内容
	 * 
	 * @param url
	 *            访问地址
	 * @param charset
	 *            字符编码
	 * @return
	 */
	public static String httpGet(final String url, final String charset) {
		try {
			httpClient();
			HttpGet httpGet = new HttpGet(url);
			HttpResponse response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();

			String content = EntityUtils.toString(entity, charset);
			
			return content;

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
}